package com.hyg.lib_common.ThirdSDK;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.util.Log;

import java.io.File;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.hyg.lib_base.lisener.AppUpdateListener;
import com.hyg.lib_common.DataUtil.UserSPUtils;
import com.hyg.lib_common.sweetalertdialog.SweetAlertDialog;
import com.pgyersdk.Pgyer;
import com.pgyersdk.update.DownloadFileListener;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;
import com.pgyersdk.update.javabean.AppBean;
//import cn.pedant.SweetAlert.SweetAlertDialog;

public class PuGongYing {

    private SweetAlertDialog progressDialog;
    private static Context mcontext;

    public PuGongYing() {

    }

    public void getUpdateVersion(final Context context, final boolean IsShowText,boolean isSystemSetting, AppUpdateListener listener) {
        mcontext = context;
        SweetAlertDialog pDialog = new SweetAlertDialog(context, SweetAlertDialog.SUCCESS_TYPE);
        /** 新版本 **/
        Pgyer.setAppId("912ab22bdedfcdcc34e0436cc8db41a0");
        new PgyUpdateManager.Builder()
                .setForced(true)                //设置是否强制提示更新,非自定义回调更新接口此方法有用
                .setUserCanRetry(false)         //失败后是否提示重新下载，非自定义下载 apk 回调此方法有用
                .setDeleteHistroyApk(false)     // 检查更新前是否删除本地历史 Apk， 默认为true
                .setUpdateManagerListener(new UpdateManagerListener() {
                    @Override
                    public void onNoUpdateAvailable() {
                        if (IsShowText) {
                            SweetAlertDialog  pDialog = new SweetAlertDialog(context, SweetAlertDialog.SUCCESS_TYPE);
                            pDialog.setTitleText("版本更新");
                            pDialog.setContentText("当前无更新，敬请期待！");
                            pDialog.setConfirmButton("好的", new SweetAlertDialog.OnSweetClickListener() {
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismiss();
                                }
                            });
                            pDialog.show();
                        }
                        //没有更新是回调此方法
                        Log.d("pgyer", "there is no new version");
                        if(listener!=null){
                            listener.onNoUpdateVersion();
                        }

                    }

                    @Override
                    public void onUpdateAvailable(final AppBean appBean) {
                        if (!isSystemSetting && UserSPUtils.getUserVersionSetting(context).equalsIgnoreCase("true")
                                && UserSPUtils.getUserVersionCode(context).equalsIgnoreCase(appBean.getVersionName())) {
                            if (listener != null) {
                                listener.onNoUpdateVersion();
                            }
                            return;
                        }
                        //有更新回调此方法
                        Log.d("pgyer", "there is new version can update"
                                + "new versionCode is " + appBean.getVersionCode());
                        //调用以下方法，DownloadFileListener 才有效；
                        //如果完全使用自己的下载方法，不需要设置DownloadFileListener
//                      pDialog = new SweetAlertDialog(context, SweetAlertDialog.SUCCESS_TYPE);
                        pDialog.setTitleText("版本更新");
                        pDialog.setContentText("是否开始下载更新?");
                        pDialog.setCancelable(false);
                        pDialog.setConfirmButton("好的", new SweetAlertDialog.OnSweetClickListener() {
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                PgyUpdateManager.downLoadApk(appBean.getDownloadURL());
                                pDialog.dismiss();
                                if (listener != null) {
                                    listener.onStart();
                                }
                            }
                        });
                        pDialog.setCancelButton("取消", new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                if(pDialog.getCheckState()){
                                    UserSPUtils.putVersionSetting(context, "true", appBean.getVersionName());
                                }
                                if (pDialog.isShowing())
                                    pDialog.dismiss();
                                if (listener != null) {
                                    listener.onCancel();
                                }
                            }
                        });
                        pDialog.show();

                        if(!isSystemSetting){
                            pDialog.setCheckBox();
                        }
                    }

                    @Override
                    public void checkUpdateFailed(Exception e) {
                        //更新检测失败回调
                        //更新拒绝（应用被下架，过期，不在安装有效期，下载次数用尽）以及无网络情况会调用此接口
                        Log.e("pgyer", "check update failed ", e);
                        if (listener != null) {
                            listener.onFail();
                        }
                    }
                })
                //注意 ：
                //下载方法调用 PgyUpdateManager.downLoadApk(appBean.getDownloadURL()); 此回调才有效
                //此方法是方便用户自己实现下载进度和状态的 UI 提供的回调
                //想要使用蒲公英的默认下载进度的UI则不设置此方法
                .setDownloadFileListener(new DownloadFileListener() {
                    @Override
                    public void downloadFailed() {
                        //下载失败
                        Log.e("pgyer", "download apk failed");
//                        SweetAlertDialog pDialog = new SweetAlertDialog(context, SweetAlertDialog.SUCCESS_TYPE);
//                        pDialog.setTitleText("版本更新");
//                        pDialog.setContentText("最新版本下载失败");
//                        pDialog.setConfirmButton("知道了,下次重试", new SweetAlertDialog.OnSweetClickListener() {
//                            public void onClick(SweetAlertDialog sweetAlertDialog) {
//                                sweetAlertDialog.dismiss();
//                            }
//                        });
//                        pDialog.show();
                        if (listener != null) {
                            listener.onFail();
                        }
                    }

                    @Override
                    public void downloadSuccessful(File file) {
                        Log.e("pgyer", "download apk success");
                        // 使用蒲公英提供的安装方法提示用户 安装apk
                        if (isNeedCheck) {//检测权限获取
                            checkPermissions(needPermissions);
                        }
                        if (listener != null) {
                            listener.onFail();
                        }
                        PgyUpdateManager.installApk(file);
                    }

                    @Override
                    public void onProgressUpdate(Integer... integers) {
                        Log.e("pgyer", "update download apk progress" + integers[0]);
                        if (listener != null) {
                            listener.onProgress(integers[0]);
                        }
                    }
                })
                .register();
    }

    @SuppressLint("NewApi")
    /**
     * 需要进行检测的权限数组
     */
    protected static String[] needPermissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.REQUEST_INSTALL_PACKAGES
    };
    public static final int PERMISSON_REQUESTCODE = 0;
    /**
     * 判断是否需要检测，防止不停的弹框
     */
    public static boolean isNeedCheck = true;

    public static void checkPermissions(String[] permissions) {
        if (
                ActivityCompat.checkSelfPermission(mcontext, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                        ActivityCompat.checkSelfPermission(mcontext, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                        ActivityCompat.checkSelfPermission(mcontext, Manifest.permission.REQUEST_INSTALL_PACKAGES) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions((AppCompatActivity) mcontext, permissions, PERMISSON_REQUESTCODE);
        }
    }

    /**
     * 检测是否所有的权限都已经授权
     */
    public boolean verifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

}
